package org.example.openhtmltopdf.controller;

import com.openhtmltopdf.outputdevice.helper.BaseRendererBuilder;
import com.openhtmltopdf.pdfboxout.PdfRendererBuilder;
import freemarker.template.Configuration;
import freemarker.template.Template;
import jakarta.servlet.http.HttpServletResponse;
import org.jsoup.Jsoup;
import org.jsoup.helper.W3CDom;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    @Qualifier("config")
    private Configuration cfg ;

    // 生成PDF
    @GetMapping("/gen")
    public Object gen(HttpServletResponse response) {
        // 设置文件下载Header
        String fileName = new String("用户列表.pdf".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1) ;
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.setContentType("application/octet-stream") ;
        try {
            // 获取模板
            Template template = this.cfg.getTemplate("users.ftl") ;
            // 准备模板需要的数据
            Map<String, Object> root = new HashMap<>() ;
            root.put("users", DATAS) ;
            // 生成HTML内容到内存中
            ByteArrayOutputStream baos = new ByteArrayOutputStream() ;
            Writer out = new OutputStreamWriter(baos) ;
            template.process(root, out) ;

            // 将上面生成的HTML内容进行解析
            Document document = Jsoup.parse(baos.toString(StandardCharsets.UTF_8), "UTF-8") ;
            // 设置HTML语法
            document.outputSettings().syntax(Document.OutputSettings.Syntax.html) ;
            // 构建PDF文档，最后将上面的Document进行输出
            PdfRendererBuilder builder = new PdfRendererBuilder();
            // 使用字体，字体名要与模板中CSS样式中指定的字体名相同
            builder.useFont(new ClassPathResource("/fonts/BabelStoneHan.ttf").getFile(), "BabelStoneHan", 1, BaseRendererBuilder.FontStyle.NORMAL, true);
            builder.toStream(response.getOutputStream()) ;
            builder.useFastMode() ;
            builder.withW3cDocument(new W3CDom().fromJsoup(document), new ClassPathResource("/templates/").getPath());
            builder.run() ;
        } catch (Exception e) {
            e.printStackTrace() ;
        }
        return "生成成功" ;
    }


    private static final List<User> DATAS = new ArrayList<>() ;
    static {
        for (int i = 0; i < 10; i++) {
            DATAS.add(new User(
                    i + 0L,
                    "姓名 - " + i,
                    new Random().nextInt(3) % 2 == 0 ? "男" : "女",
                    "身份证 - " + i,
                    new Random().nextInt(100),
                    i + "@qq.com",
                    "avatar.png") // 头像实际在模板中写死了
            ) ;
        }
    }
}
